package pro.ticktock.tools.mbconv;

import org.apache.poi.hwpf.converter.WordToTextConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by lambert on 2017/8/21.
 */
public class ClassicDiskRecommended {
  private static Logger logger = LoggerFactory.getLogger(ClassicDiskRecommended.class);

  static int unmatchCount = 0;
  static int matchCount = 0;
  static int paraCount = 0;
  static int workCount = 0;
  static void finishPara() {
    paraCount++;
  }

  static void allFinished() {
    logger.info("Paragraph count: {}.", paraCount);
    logger.info("Matched/Unmatched brackets: {}/{}.", matchCount, unmatchCount);
    logger.info("Art work count: {}.", workCount);
  }

  static String getRootDir() {
    return "H:\\PDFs\\processed\\经典唱片版本收藏推荐\\";
  }

  static String fileName = "经典唱片版本收藏推荐.doc";

  private static String finalFileName = "recoindex";

  public static void main(String[] args) throws Exception {


    String archiveDir = "H:\\PDFs\\docs\\";

    String txtFileName = "经典唱片版本收藏推荐.txt";
    AbstractPass.setRootDir(getRootDir());
    Path output = Paths.get(getRootDir() + txtFileName);
    if (Files.exists(output)) Files.delete(output);
    Charset charset = StandardCharsets.UTF_8;


    WordToTextConverter.main(
            new String[] {
                    archiveDir + fileName,
                    getRootDir() + txtFileName});
    Pass1 p1 = new Pass1(txtFileName);
    p1.process();
    Pass3 p3 = new Pass3(txtFileName, p1.getResultFileName());
    p3.process();
    Pass4 p4 = new Pass4(txtFileName, p3.getResultFileName());
    p4.process();
    Pass5 p5 = new Pass5(txtFileName, p4.getResultFileName());
    p5.process();
    FinalPass fp = new FinalPass(txtFileName, p5.getResultFileName());
    fp.process();

    /*
    Path p = Paths.get(getRootDir() + p2.getResultFileName());
    List<String> lines = Files.readAllLines(p, charset);
    Files.write(output, lines, charset, StandardOpenOption.CREATE,
            StandardOpenOption.APPEND);


    String inputFile = mergedFileName;
    for (int j = 3; j <= LAST_PASS; j++) {
      Pass p = (Pass)Pass.class.forName("nconv.convert.musicbible.Pass" + j)
              .getDeclaredConstructor(String.class, String.class)
              .newInstance(j < LAST_PASS ? mergedFileName : finalFileName, inputFile);
      p.process();
      inputFile = ((AbstractPass)p).getResultFileName();
    }
    */
  }

  static class FinalPass extends AbstractPass {
    public FinalPass(String origSrcFileName, String srcFileName) throws IOException {
      super(origSrcFileName, srcFileName);
    }

    @Override
    protected void doProcess() throws IOException {
      String line;
      Pattern cnChars = Pattern.compile("[\u4e00-\u9fa5]+");
      String category = null;

      StringBuffer content = new StringBuffer();
      List<String> cates = new ArrayList<>();
      List<String> authors = new ArrayList<>();
      Map<String, List<String>> worksOnAuthor = new HashMap<>();
      Map<String, Pair<List<String>, Map<String, List<String>>>> cateAuthors = new HashMap<>();
      String author = null;

      while ((line = srcReader.readLine()) != null) {
        String noSpaceLine = line.replace(" ", "");
        Matcher m = cnChars.matcher(noSpaceLine);
        if (m.find()) {
          int len = m.end() - m.start();
          if (len == noSpaceLine.length()) {
            if (content.length() > 0) {
              worksOnAuthor.get(author).add(content.toString());
            }

            category = noSpaceLine;
            cates.add(category);
            authors = new ArrayList<String>();
            worksOnAuthor = new HashMap<String, List<String>>();
            cateAuthors.put(category, new Pair<List<String>, Map<String, List<String>>>(authors, worksOnAuthor));
            author = null;
            continue;
          }
        }
        if (line.startsWith(" ") && line.indexOf('：') > 0) {
          line = line.trim();
          int smIdx = line.indexOf('：');
          if (content.length() > 0) {
            if (author != null) {
              worksOnAuthor.get(author).add(content.toString());
            }
          }
          author = line.substring(0, smIdx);
          if (!worksOnAuthor.containsKey(author)) {
            authors.add(author);
            List<String> works = new ArrayList<>();
            worksOnAuthor.put(author, works);
          }
          content = new StringBuffer(line.substring(smIdx + 1));
        } else {
          content.append(line);
        }
      }

      if (content.length() > 0) {
        worksOnAuthor.get(author).add(content.toString());
      }

      Random rand = new Random();
      AtomicInteger it = new AtomicInteger(1);
      List<String> pageNames = cates.stream().map(a -> "page" + Math.abs(rand.nextLong()) + "i" + it.getAndIncrement()).collect(Collectors.toList());

      BufferedWriter writer = new BufferedWriter(new FileWriter(new File(getRootDir() + "title.html")));
      for (int i = 0; i < cates.size(); i++) {
        writer.append("<a href=\""  + pageNames.get(i) + ".html\" target=\"content\">" + cates.get(i) + "</a><br/>");
      }
      writer.close();

      for (int i = 0; i < cates.size(); i++) {
        String cate = cates.get(i);
        writer = new BufferedWriter(new FileWriter(new File(getRootDir() + pageNames.get(i) + ".html")));
        Pair<List<String>, Map<String, List<String>>> pair = cateAuthors.get(cate);
        writer.append("<html><head>");
        /*
        writer.append("<style type=\"text/css\">\n" +
                "table.imagetable {\n" +
                "\tfont-family: verdana,arial,sans-serif;\n" +
                "\tfont-size:11px;\n" +
                "\tcolor:#333333;\n" +
                "\tborder-width: 1px;\n" +
                "\tborder-color: #999999;\n" +
                "\tborder-collapse: collapse;\n" +
                "}\n" +
                "table.imagetable th {\n" +
                "\tbackground:#b5cfd2 url('cell-blue.jpg');\n" +
                "\tborder-width: 1px;\n" +
                "\tpadding: 8px;\n" +
                "\tborder-style: solid;\n" +
                "\tborder-color: #999999;\n" +
                "}\n" +
                "table.imagetable td {\n" +
                "\tbackground:#dcddc0 url('cell-grey.jpg');\n" +
                "\tborder-width: 1px;\n" +
                "\tpadding: 8px;\n" +
                "\tborder-style: solid;\n" +
                "\tborder-color: #999999;\n" +
                "}\n" +
                "</style>"); */
        writer.append("<link href=\"common/table.css\" rel=\"stylesheet\" type=\"text/css\" />");
        writer.append("<script type=\"text/javascript\" src=\"common/table.js\"></script>");
        writer.append("</head><body>");
        writer.append("<table border=\"1\" class=\"altrowstable\" id=\"alternatecolor\"><tr><th>作曲家</th><th>作品</th></tr>");
        for (String anAuthor : pair.first) {
          List<String> works = pair.second.get(anAuthor);
          writer.append("<tr><td rowspan=\"" + works.size() + "\">")
                  .append(anAuthor + "</td>");
          for (int j = 0; j < works.size(); j++) {
            String work = works.get(j);
            if (j > 0) {
              writer.append("<tr>");
            }
            writer.append("<td>" + work + "</td>");
            writer.append("</tr>");
          }
          writer.append("</tr>");
        }


        writer.append("</table>");

        writer.append("</body></html>");
        writer.close();
      }

    }

  }
}

